const { Sequelize, DataTypes, Op } = require("sequelize");
const { doSqlMiddle, JSONParse, JSONStringify } = require("../utils/tool");
const { sqlLog } = require("../utils/logger");
const path = require("path");
const { ErrorModel } = require("../model/resModel");

const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: path.join(__dirname, `../storage/project.sqlite`),
  logging: (msg) => {
    // 只记录第一个参数
    sqlLog.info(msg);
  },
});

/**
 * # 用户表的定义
 */
const Project = sequelize.define("Project", {
  id: {
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV1,
    unique: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    defaultValue: "默认用户名",
  },
  userId: {
    type: DataTypes.UUID,
  },
  projectIncome: {
    // 项目总收入
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
  rooms: {
    type: DataTypes.TEXT,
    defaultValue: "[]",
    get() {
      return JSONParse(this.getDataValue("rooms"));
    },
    set(value) {
      this.setDataValue("rooms", JSONStringify(value));
    },
  },
});

async function createProject(data) {
  return doSqlMiddle(async () => {
    let res = await Project.create(data);
    return res;
  });
}

async function findProject({ limit, page, id, userId, name } = {}, needPs = false) {
  const query = {
    attributes: { exclude: ["ps"] }, // 排除密码
    where: {},
  };
  if (needPs) {
    delete query.attributes;
  }
  if (limit) {
    query.limit = limit;
  }
  if (page) {
    query.offset = page * limit;
  }
  if (name) {
    query.where.name = {
      [Op.like]: `%${name}%`, // 模糊匹配姓名
    };
  }
  if (userId) {
    query.where.userId = userId;
  }
  if (id) {
    query.where.id = id;
  }

  if (Object.keys(query.where).length <= 0) {
    delete query.where;
  }

  return doSqlMiddle(async () => {
    let res = await Project.findAll(query);
    return res;
    // return res.map((item) => {
    //   return parseJsonByKeys(item.toJSON(), NeedJSONKeys);
    // });
  });
}

async function updateProject(projectId, data) {
  return doSqlMiddle(async () => {
    const project = await Project.findOne({ where: { id: projectId } });
    if (!project) {
      return new ErrorModel("工程不存在");
    }
    let res = Project.update(data, {
      where: { id: projectId },
    });
    if (res.err) {
      return res;
    }
    res = await Project.findOne({ where: { id: projectId } });
    return res.toJSON();
  });
}

async function deleteProject(projectId) {
  return doSqlMiddle(async () => {
    return await Project.destroy({
      where: {
        id: projectId,
      },
    });
  });
}

module.exports = {
  Project,
  sequelize,
  findProject,
  createProject,
  updateProject,
  deleteProject,
};
